//
//  MainTabController.swift
//  Weibo-Swift
//
//  Created by LYFDevelopment on 2017/4/11.
//  Copyright © 2017年 LYFDevelopment. All rights reserved.
//

import UIKit

class MainTabController: UITabBarController {
    
    lazy var composeBtn = UIButton.init(backGrundImage: UIImage.init(named: "tabbar_compose_button"), image: UIImage.init(named: "tabbar_compose_icon_add"))
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setUpViewControllers()
        setUpConposeBtn()
    }
    //设置设备方向支持,当有视频播放时 一般用modal形式
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
}
//extension 相当于OC 中的分类，在swift中可以用来切分代码块
//可以吧功能相近的函数放在一个extension中
//extension中不能定义出计算属性歪的属性
//MARK:- 设置所有子视图
extension MainTabController{
    
     func setUpConposeBtn(){
        tabBar.addSubview(composeBtn)
        
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width/count
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 1)
    }
    //设置所有子控制器
    
     func setUpViewControllers(){
        let arrayM = [["className":"HomeViewController","title":"首页","imageName":"tabbar_home"],["className":"MessageViewController","title":"消息","imageName":"tabbar_message_center"],["className":"UIViewController"],["className":"DiscoveryViewController","title":"发现","imageName":"tabbar_discover"],["className":"ProfileViewController","title":"我的","imageName":"tabbar_profile"],]
        var arr = [UIViewController]()
        for dict in arrayM{
            let vc = setUpChildController(dict)
            arr.append(vc)
        }
        viewControllers = arr
    }
    //使用字典创建一个子控制器
    fileprivate func setUpChildController(_ dict: [String:String])->UIViewController{
        //取得字典内容
        guard let clsName = dict["className"],let title = dict["title"],let imageName = dict["imageName"],        let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? UIViewController.Type
            else {
            return UIViewController()
        }
        //创建视图控制器

        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        vc.tabBarItem!.title = title
        vc.tabBarItem.image = UIImage.init(named: imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage.init(named: imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        let nav = NavgaitonController.init(rootViewController: vc)
        return nav
    }
}
